//
//  listFontAppDelegate.m
//  listFont
//
//  Created by xiewei.max@gmail.com on 09-11-29.
//  Copyright xiewei.max@gmail.com 2009. All rights reserved.
//

#import "listFontAppDelegate.h"
#import "AboutView.h"
#import "AdMobView.h"

@implementation listFontAppDelegate

@synthesize window;

NSMutableArray *m_fontFamilyArray;
NSMutableDictionary *m_fontDictionary;	// fontFamily -> fonts array

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

	//window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
	window = [[UIWindow alloc] initWithFrame: CGRectMake(0, 20, 320, 480)];
	window.backgroundColor = [UIColor groupTableViewBackgroundColor];
	
	// Request an ad
	adMobAd = [AdMobView requestAdWithDelegate:self]; // start a new ad request
	[adMobAd retain]; // this will be released when it loads (or fails to load)
	
	m_tableView = [[UITableView alloc] initWithFrame: CGRectMake(0, 0, 320, 460)];
	m_tableView.dataSource = self;
	m_tableView.delegate = self;
	m_tableView.backgroundColor = [UIColor clearColor];
	
	[window addSubview: m_tableView];
	
	UIButton *infoButton = [UIButton buttonWithType: UIButtonTypeInfoLight];
	infoButton.frame = CGRectMake(280, 420, 20, 20);
	[infoButton addTarget: self action: @selector(openAboutView) forControlEvents: UIControlEventTouchUpInside];
	[window addSubview: infoButton];
	
	[self initFontsArray];
	
    // Override point for customization after application launch
    [window makeKeyAndVisible];
}


- (void)dealloc {
	[adMobAd release];
	[refreshTimer invalidate];
	
    [window release];
    [super dealloc];
}

-(void) initFontsArray
{
	m_fontFamilyArray = [[NSMutableArray alloc] init];
	m_fontDictionary = [[NSMutableDictionary alloc] init];
	
	NSArray *familyNames = [UIFont familyNames];  
    for( NSString *familyName in familyNames )
	{  
		printf( "Family: %s \n", [familyName UTF8String] );  
		
		[m_fontFamilyArray addObject: familyName];
		NSMutableArray *fontArray = [[NSMutableArray alloc] init];
		
		NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];  
		for( NSString *fontName in fontNames )
		{
			[fontArray addObject: fontName];
			printf( "\tFont: %s \n", [fontName UTF8String] );  
		}  
		
		[m_fontDictionary setObject: fontArray forKey: familyName];
	}
}
	
-(void) openAboutView
{
	if(nil == m_aboutView)
	{
		m_aboutView = [[AboutView alloc] initWithFrame: CGRectMake(0, 0, 320, 460)];

	}
	
	[UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.75];
    [UIView setAnimationDelegate: self];
    [UIView setAnimationDidStopSelector:@selector(transitionDidStop:finished:context:)];
	
	[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView: window cache:YES];
	[window addSubview: m_aboutView];
	
	[UIView commitAnimations];
}

#pragma mark -

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
	return [[m_fontDictionary objectForKey: [m_fontFamilyArray objectAtIndex: section]] count];
	
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString* cellViewIdentifier = @"cellViewIdentifier";
    
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellViewIdentifier];
	if (cell == nil) 
    {
		cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault 
											  reuseIdentifier: cellViewIdentifier] autorelease];
        
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
	}
	
	NSString *fontName = [[m_fontDictionary objectForKey: [m_fontFamilyArray objectAtIndex: indexPath.section]] objectAtIndex: indexPath.row];
	
	int fontSize = 18;
	
	cell.textLabel.text = [NSString stringWithFormat: @"%@\n字体大小/Font Size: %d\n"
						   "01234567890\n"
						   "abcdefghijklmnopqrstuvwxyz\n"
						   "ABCDEFGHIJKLMNOPQRSTUVWXYZ", fontName, fontSize];
    cell.textLabel.font = [UIFont fontWithName: fontName size: fontSize];
	cell.textLabel.numberOfLines = 0;

	return cell;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [m_fontFamilyArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [NSString stringWithFormat: @"%02d %@", section, [m_fontFamilyArray objectAtIndex: section]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	NSString *fontName = [[m_fontDictionary objectForKey: [m_fontFamilyArray objectAtIndex: indexPath.section]] objectAtIndex: indexPath.row];
	
	int fontSize = 18;
	
	NSString *cellText = [NSString stringWithFormat: @"%@\n字体大小/Font Size: %d\n"
						   "01234567890\n"
						   "abcdefghijklmnopqrstuvwxyz\n"
						   "ABCDEFGHIJKLMNOPQRSTUVWXYZ", fontName, fontSize];

	CGSize aSize;
	aSize = [cellText sizeWithFont: [UIFont fontWithName: fontName size: fontSize]
				constrainedToSize: CGSizeMake(300.0f, 1000.0f)
					lineBreakMode: UILineBreakModeClip];
	
	return aSize.height + 10.0f;
	
}

#pragma mark -

// Request a new ad. If a new ad is successfully loaded, it will be animated into location.
- (void)refreshAd:(NSTimer *)timer 
{
	[adMobAd requestFreshAd];
}

#pragma mark AdMobDelegate methods

- (NSString *)publisherId {
	return @"a14b4c3fca3b66b"; // xiewei.max@gmail.com, font list
}

- (UIColor *)adBackgroundColor {
	return [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; // this should be prefilled; if not, provide a UIColor
}

- (UIColor *)primaryTextColor {
	return [UIColor colorWithRed:1 green:1 blue:1 alpha:1]; // this should be prefilled; if not, provide a UIColor
}

- (UIColor *)secondaryTextColor {
	return [UIColor colorWithRed:1 green:1 blue:1 alpha:1]; // this should be prefilled; if not, provide a UIColor
}

- (BOOL)mayAskForLocation {
	return NO; // this should be prefilled; if not, see AdMobProtocolDelegate.h for instructions
}

// To receive test ads rather than real ads...

/*
 - (BOOL)useTestAd {
 return YES;
 }
 
 - (NSString *)testAdAction {
 return @"url"; // see AdMobDelegateProtocol.h for a listing of valid values here
 }
*/

// Sent when an ad request loaded an ad; this is a good opportunity to attach
// the ad view to the hierachy.
- (void)didReceiveAd:(AdMobView *)adView {
	NSLog(@"AdMob: Did receive ad");
	
	// put the ad at the bottom of the screen
	adMobAd.frame = CGRectMake(0, 0, 320, 48);
	m_tableView.frame = CGRectMake(0, 48, 320, 480 - 68);
	
	[window addSubview:adMobAd];
	[refreshTimer invalidate];
	
	refreshTimer = [NSTimer scheduledTimerWithTimeInterval: 30.0 target:self selector:@selector(refreshAd:) userInfo:nil repeats:YES];
}

// Sent when an ad request failed to load an ad
- (void)didFailToReceiveAd:(AdMobView *)adView {
	NSLog(@"AdMob: Did fail to receive ad");
	[adMobAd release];
	adMobAd = nil;
	// we could start a new ad request here, but in the interests of the user's battery life, let's not
}

@end
